package com.sluggard.ai.service.impl;

import com.sluggard.ai.manage.DynamicMcpManager;
import com.sluggard.ai.manage.VectorStoreManage;
import com.sluggard.ai.constants.ChatConstant;
import com.sluggard.ai.model.req.ChatReq;
import com.sluggard.ai.service.ChatService;
import io.modelcontextprotocol.client.McpAsyncClient;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.mcp.AsyncMcpToolCallbackProvider;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;
import reactor.core.publisher.Flux;

import java.time.Duration;
import java.util.Objects;

/**
 * 类描述：
 *
 * @author lizheng
 * @created 2025/4/22 16:48
 */
@Slf4j
@Service
public class ChatServiceImpl implements ChatService {

    @Resource
    ChatClient chatClient;

    private String promptTemplate = """
            你是一个智能系统助手
            
            用户的问题：{message}
            请用中文回答
            """;

    @Override
    public Flux<String> chatStream(ChatReq chatReq) {
        ChatClient.ChatClientRequestSpec advisors = chatClient
                .prompt()
                .advisors(advisor -> advisor.param(ChatConstant.CHAT_MEMORY_CONVERSATION_ID, chatReq.getConversationId())
                        .param(ChatConstant.CHAT_MEMORY_RESPONSE_SIZE, 20));

        if (Objects.nonNull(chatReq.getKnowledgeId())) {
            advisors.advisors(new QuestionAnswerAdvisor(VectorStoreManage.getVectorStore(chatReq.getKnowledgeId())));
        }
        AsyncMcpToolCallbackProvider asyncMcpToolCallbackProvider = DynamicMcpManager.asyncMcpToolCallbackProvider(chatReq.getMcpServers());
        if (Objects.nonNull(asyncMcpToolCallbackProvider)) {
            advisors.tools(asyncMcpToolCallbackProvider);
        }
        String question = StringUtils.replace(promptTemplate, "{message}", chatReq.getMessage());
        if(!chatReq.getDeepThink()){
            question += "/no_think";
        }
        return advisors.user(question)
                .stream()
                .content()
                .doOnError(throwable -> log.error("chat error: {}", throwable.getMessage()));
    }

}
